﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HYBYSoft.Company.Models;
using HYBYSoft.Company.WebSite.Helper;
using System.Text;

namespace HYBYSoft.Company.WebSite
{
    public class AuthenticationAttribute : FilterAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        CompanySiteEntities _dbContext = new CompanySiteEntities();

        #region IAuthorizationFilter 成员

        /// <summary>
        /// 授权验证
        /// </summary>
        /// <param name="filterContext">筛选器上下文</param>
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            //获得Cookie中的令牌信息
            HttpCookie token = filterContext.HttpContext.Request.Cookies[ConstDefinition.TOKEN_NAME];

            //检查是否获得有效的令牌信息
            if (token == null || string.IsNullOrEmpty(token.Value))
            {
                filterContext.Result = new RedirectResult("~/Admin/Login/Login");
                return;
            }

            //对令牌信息进行拆分处理
            byte[] tokenByteArray = Convert.FromBase64String(token.Value);
            string[] cookiesInfo = (Encoding.UTF8.GetString(tokenByteArray)).Split('$');

            //检查是否获得有效的令牌信息
            if (cookiesInfo.Length != 4)
            {
                filterContext.Result = new RedirectResult("~/Admin/Login/Login");
                return;
            }

            int id = 0;
            int.TryParse(cookiesInfo[0], out id);
            string name = cookiesInfo[1];

            //根据用户名在数据库中查找用户
            var member = _dbContext.Admins.SingleOrDefault(m => m.AdminID == id && m.State != 0);

            //检查是否获得用户信息，并且用户信息是否与登录信息一致
            if (member == null || member.Name != name)
                filterContext.Result = new RedirectResult("~/Admin/Login/Login");

        }

        #endregion
    }
}